<template>
  <div>
    <a-card title="用户信息修改" :bordered="false">
      <div>
        <a-tabs defaultActiveKey="1" :tabPosition="tabPosition">
          <a-tab-pane tab="个人信息" key="1">
            <div>
              <a-row :gutter="12">
                <a-col :md="12" :sm="24">
                  <a-form :form="infoForm">
                    <a-form-item
                      label="用户名"
                      :labelCol="labelCol"
                      :wrapperCol="wrapperCol"
                    >
                      <a-input v-decorator="['userName', {initialValue: user.userName, rules: [{required: true, message: '请输入用户姓名', trigger: 'blur'}]}]" />
                    </a-form-item>
                    <a-form-item
                      label="个人介绍"
                      :labelCol="labelCol"
                      :wrapperCol="wrapperCol"
                    >
                      <a-textarea v-decorator="['userInfo', {initialValue: user.userInfo}]" style="height: 70px;"/>
                    </a-form-item>
                    <a-form-item
                      label="性别"
                      :labelCol="labelCol"
                      :wrapperCol="wrapperCol"
                    >
                      <a-radio-group v-decorator="['userSex', {initialValue: user.userSex}]">
                        <a-radio :value="0">保密</a-radio>
                        <a-radio :value="1">男</a-radio>
                        <a-radio :value="2">女</a-radio>
                      </a-radio-group>
                    </a-form-item>
                  </a-form>
                </a-col>
                <a-col :md="1"></a-col>
                <a-col :md="6" style="height: 180px;width: 180px">
                  <img v-if="user.imageUrl!== null" :src="preUrl + user.imageUrl" style="height: 180px;width: 180px"/>
                  <img v-else :src="preUrl + defaultImage" style="height: 180px;width: 180px"/>
                  <a-row style="text-align: center">
                    <a-upload
                      name="avatar"
                      class="avatar-uploader"
                      :show-upload-list="false"
                      :before-upload="() => { return false }"
                      @change="handleChange">
                      <a-button v-if="user.imageUrl!== null" style="margin-top: 20px;border-radius: 15px">修改头像</a-button>
                      <a-button v-else style="margin-top: 20px;border-radius: 15px">上传头像</a-button>
                    </a-upload>
                  </a-row>
                </a-col>
              </a-row>
              <a-form-item>
                <a-button type="primary" @click="submitInfo" style="margin-left: 280px">提交</a-button>
              </a-form-item>
            </div>
          </a-tab-pane>
          <a-tab-pane tab="修改密码" key="2">
            <div class="table-page-search-wrapper">
              <a-row :gutter="12">
                <a-col :md="12" :sm="24">
                  <a-form :form="pwdForm">
                    <a-form-item
                      label="原密码"
                      :labelCol="newLabelCol"
                      :wrapperCol="newWrapperCol"
                    >
                      <a-input-password
                        v-decorator="['password', {rules: [
                          { required: true, message: '请输入原密码', trigger: 'blur' },
                          { validator: validatePwd, trigger: 'blur' }]}]" />
                    </a-form-item>
                    <a-form-item
                      label="新密码"
                      :labelCol="newLabelCol"
                      :wrapperCol="newWrapperCol"
                    >
                      <a-input-password
                        v-decorator="['loginPwd', {rules: [
                          { required: true, message: '请输入新密码', trigger: 'blur' },
                          { validator: validatePwd, trigger: 'blur' }]}]" />
                    </a-form-item>
                    <a-form-item
                      label="确认密码"
                      :labelCol="newLabelCol"
                      :wrapperCol="newWrapperCol"
                    >
                      <a-input-password
                        v-decorator="['confirmPwd', {rules: [
                          { required: true, message: '请再次确认密码', trigger: 'blur' },
                          { validator: confirmPwd, trigger: 'blur' }]}]" />
                    </a-form-item>
                  </a-form>
                </a-col>
              </a-row>
              <a-form-item>
                <a-button type="primary" @click="submitPwd" style="margin-left: 280px">提交</a-button>
              </a-form-item>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-card>
    <edit-image ref="editImage" @ok="handleOk"/>
  </div>
</template>
<script>
  import md5 from 'md5'
  import { getByUserId, update, resetPwd, changeImage } from '@/api/basic/user'
  import { TreeSelect } from 'ant-design-vue'
  import EditImage from '@/views/music/modules/selfCenter/EditImage'
  import { upload } from '@/api/file/file'
  function getBase64 (img, callback) {
    const reader = new FileReader()
    reader.addEventListener('load', () => callback(reader.result))
    reader.readAsDataURL(img)
  }
  export default {
    components: {
      ATreeSelect: TreeSelect,
      EditImage
    },
    data () {
      return {
        tabPosition: 'left',
        // 表单对象
        user: {},
        file: {},
        imageUrl: '',
        img: '',
        preUrl: '/api/file/download/image/',
        defaultImage: 'default.jpg',
        expandedKeys: [1],
        treeData: [],
        avatar: '',
        labelCol: {
          xs: { span: 24 },
          sm: { span: 7 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        newLabelCol: {
          xs: { span: 24 },
          sm: { span: 7 }
        },
        newWrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        infoForm: this.$form.createForm(this),
        pwdForm: this.$form.createForm(this)
      }
    },
    created () {
      getByUserId()
        .then(res => {
          this.user = res.data.result
          if (this.user.userSex === null) {
            this.user.userSex = 0
          }
        })
    },
    methods: {
      handleOk (newImageUrl) {
        this.imageUrl = newImageUrl
        this.file = this.toFile(newImageUrl)
        if (this.file.type !== undefined) {
          const formData = new FormData()
          formData.append('file', this.file)
          formData.append('type', 'image')
          upload(formData)
            .then(res => {
              if (res.data.message !== 'error') {
                console.log(res.data)
                this.user.imageUrl = res.data.result.saveName
                changeImage({ 'imageUrl': this.user.imageUrl })
                  .then(res => {
                    if (res.data.message !== 'error') {
                      this.$store.getters.userInfo.avatar = this.user.imageUrl
                      this.$message.success('头像修改成功！')
                    } else {
                      this.$message.error('头像修改失败！')
                    }
                  })
              } else {
                this.$message.error('头像上传失败！')
              }
            })
        }
      },
      toFile (dataurl) {
        const arr = dataurl.split(',')
        const mime = arr[0].match(/:(.*?);/)[1]
        const bstr = atob(arr[1])
        let n = bstr.length
        const u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        return new File([u8arr], this.file.name, { type: mime })
      },
      handleChange (info) {
        if (info.file.type.indexOf('image') === -1) {
          this.$message.warning('请选择图片文件')
          return
        }
        if (info.file.size / 1024 / 1024 > 2) {
          this.$message.warning('请选择不超过2MB大小的图片')
          return
        }
        this.file = info.file
        getBase64(info.file, imageUrl => {
          this.imageUrl = imageUrl
          this.$refs.editImage.edit(imageUrl, info.file.name)
        })
      },
      // 个人信息提交
      submitInfo () {
        const { infoForm: { validateFields } } = this
        validateFields((errors, values) => {
          if (!errors) {
            update(Object.assign(values, {
              'userId': this.user.userId }))
              .then(res => {
                if (res.message !== 'error') {
                  this.$emit('ok')
                  this.$store.getters.userInfo.username = values.userName
                  this.$message.success('修改成功！')
                } else {
                  this.$message.error('操作失败！')
                }
              })
          } else {
          }
        })
      },
      // 密码
      submitPwd () {
        const { pwdForm: { validateFields } } = this
        validateFields((errors, values) => {
          if (!errors) {
            if (this.user.loginPwd === md5(values.password)) {
              resetPwd(Object.assign(values, { 'userId': this.user.userId }))
                .then(res => {
                  if (res.message !== 'error') {
                    this.$message.success('密码重置成功！')
                  } else {
                    this.$message.error('操作失败！')
                  }
                })
            } else {
              this.$message.error('原密码错误！')
            }
          } else {
          }
        })
      },
      // 前端验证密码
      validatePwd (rule, value, callback) {
        const regex = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,}$/
        if (value === '' || value === undefined || value === null) {
          callback()
        } else {
          if (regex.test(value)) {
            return callback()
          } else {
            return callback(new Error('大/小写字母，数字，特殊符号四选三，长度至少6位'))
          }
        }
      },
      // 前端两次密码是否一致
      confirmPwd (rule, value, callback) {
        if (value === '' || value === undefined || value === null) {
          callback()
        } else {
          if (this.pwdForm.getFieldValue('loginPwd') === value) {
            return callback()
          } else {
            return callback(new Error('请确保两次密码输入一致'))
          }
        }
      }
    }
  }
</script>
